package com.gnerv.sylvanas.framework.plugin.init.sql;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.gnerv.sylvanas.framework.core.init.sql.BaseDatabaseInitService;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class DatabaseInitializer implements ApplicationRunner {
    
    private final DataSource dataSource;
    private final List<BaseDatabaseInitService> databaseInitServiceList;

    public DatabaseInitializer(DataSource dataSource, List<BaseDatabaseInitService> databaseInitServiceList) {
        this.dataSource = dataSource;
        this.databaseInitServiceList = databaseInitServiceList;
    }
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (dataSource instanceof DynamicRoutingDataSource dynamicRoutingDataSource) {
            dynamicRoutingDataSource.getDataSources().values().forEach(dataSource -> {
                try (Connection connection = dataSource.getConnection()) {
                    for (BaseDatabaseInitService baseDatabaseInitService : databaseInitServiceList) {
                        List<String> schemaLocationList = baseDatabaseInitService.schemaLocationList();
                        for (String schemaLocation : schemaLocationList) {
                            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
                            Resource resources = resolver.getResource(schemaLocation);
                            ScriptUtils.executeSqlScript(connection, new ClassPathResource("/db/schema.sql") );
                        }
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
}